
#include "common.fxh"

cbuffer cbPerObject
{
	float4x4 gWVP;
	float4x4 gWorld;
	float4 gDiffMat;
	float4 gSpecMat;
};

cbuffer cbPerFrame
{
	float3 gDiffLight;
	float3 gAmbLight;
	float3 gSpecLight;
	float3 gLightPosW;
	float3 gEyePosW;
};


Texture2D gDiffuseMap;

SamplerState gTriLinearSam
{
	Filter = MIN_MAG_MIP_LINEAR;
	AddressU = Wrap;
	AddressV = Wrap;
};

struct VS_IN
{
	float3 posL     : POSITION;
	float3 tangentL : TANGENT;
	float3 normalL  : NORMAL;
	float2 texC     : TEXCOORD;
};

struct VS_OUT
{
	float4 posH         : SV_POSITION;
	float3 posW         : TEXCOORD0;
	float3 normalW      : TEXCOORD1;
    float2 texC         : TEXCOORD2;
};

VS_OUT VS(VS_IN vIn)
{
	VS_OUT vOut;
	
	vOut.posH = mul(float4(vIn.posL, 1.0f), gWVP);
	vOut.posW = mul(float4(vIn.posL, 1.0f), gWorld).xyz;
	
	float3 normalW = mul(float4(vIn.normalL, 0.0f), gWorld).xyz;
	vOut.normalW = normalize(normalW);

	vOut.texC = vIn.texC;
	
	return vOut;
}


float4 PS(VS_OUT pIn) : SV_Target
{      
	float3 normalW = normalize(pIn.normalW);

	float3 lightVecW = normalize(gLightPosW - pIn.posW);
	float3 vertToEyeW = normalize(gEyePosW - pIn.posW);
  
	float3 ambient = gDiffMat * gAmbLight;
	
	float3 diffLightIntensity;
	float3 specLightIntensity;
	
	calculateLighting(normalW, lightVecW, vertToEyeW, gSpecMat.w,
		diffLightIntensity, specLightIntensity);

	float3 diffuse = diffLightIntensity * gDiffMat * gDiffLight;
	float3 specular = specLightIntensity * gSpecMat * gSpecLight;
  
	return float4( (ambient + diffuse) * gDiffuseMap.Sample(gTriLinearSam, pIn.texC) + specular, 1.0f);
}

technique10 tech
{
    pass P0
    {
        SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetGeometryShader( NULL );
        SetPixelShader( CompileShader( ps_4_0, PS() ) );
    }
}
